package com.uinnova.product.eam.workable.listener;

import com.uinnova.product.eam.workable.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.engine.HistoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.flowable.engine.history.HistoricProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Slf4j
@Component("publicAccessSingleUserInfoListener")
public class PublicAccessSingleUserInfoListener implements ExecutionListener {

    @Value("${generic.user.url}")
    private String genericUserUrl;

    @Autowired
    private transient HistoryService historyService;

    @Resource
    private HttpUtil httpUtil;

    @Override
    public void notify(DelegateExecution execution) {
        //获取当前任务的id
        FlowElement currentFlowElement = execution.getCurrentFlowElement();
        String taskDefinitionId = currentFlowElement.getDocumentation();
        log.info("当前任务定义id：{}", taskDefinitionId);
        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery()
                .processInstanceId(execution.getProcessInstanceId())
                .singleResult();
        //获取流程定义id
        String splitProcessDefinitionId = historicProcessInstance.getProcessDefinitionKey();
        log.info("当前流程定义id：{}", splitProcessDefinitionId);
        //获取当前流程实例业务主键
        String processInstanceBusinessKey = execution.getProcessInstanceBusinessKey();
        log.info("当前流程业务主键：{}", processInstanceBusinessKey);
        String requestUrl = genericUserUrl+"?defKey="+splitProcessDefinitionId+"&businessKey="+processInstanceBusinessKey+"&taskKey="+taskDefinitionId;
        log.info("获取通用审批用户请求的url:{}",requestUrl);
        List<String> userLoginCodes = httpUtil.get(requestUrl, List.class);

        if(CollectionUtils.isEmpty(userLoginCodes)){
            log.error("预评审-值班人获取为空");
            throw new RuntimeException("预评审-值班人获取为空");
        }

        log.info("下一节点评审人:{}",userLoginCodes);
        Map<String, Object> variables = execution.getVariables();
        variables.put("assignee", userLoginCodes.get(0));
        execution.setVariables(variables);
    }
}
